package com.agileai.miscdp.ui;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Text;

import com.agileai.util.StringUtil;

public class TextCheckPolicy {
	public static final String POLICY_MODEL_NAME = "MODEL_NAME"; //app、ws、mf、component
	public static final String POLICY_FOLDER_NAME = "FOLDER_NAME";//WsFolder、MfFolder
	public static final String POLICY_OPERATION_NAME = "OPERATION_NAME";//service's operation 、variable
	public static final String POLICY_PACKAGE_NAME = "OPERATION_NAME";//service's operation 、variable
	public static final String POLICY_FREE_NAME = "FREE_NAME";//service's operation 、variable
	
	private Text targetText = null;
	private String policy = null;
	
	public TextCheckPolicy(Text text,String policy){
		this.targetText = text;
		this.policy = policy;
		String content = text.getText();
		if (content != null && !content.trim().equals("")){
			targetText.setSelection(content.length());	
		}
		this.initPolicy();
	}
	
	private void initPolicy(){
		targetText.addKeyListener(new KeyAdapter() {
			int currentCursorPostion = -1;
			int currentTextLength = -1;
			public void keyPressed(KeyEvent e) {
				int start = targetText.getSelection().x;
				int end = targetText.getSelection().y;
				if (start == end){
					currentCursorPostion = start;
				}
				if (targetText.getText() != null){
					currentTextLength = targetText.getText().length();					
				}
			}
			@Override
			public void keyReleased(KeyEvent e) {
				if ((e.stateMask == SWT.SHIFT && e.keyCode == SWT.HOME)
						|| (e.stateMask == SWT.SHIFT && e.keyCode == SWT.END)
						|| (e.stateMask == SWT.CTRL && e.keyCode == 'c')
						){
					return;
				}
				if (e.stateMask == SWT.CTRL && e.keyCode == 'v'){
					currentTextLength = targetText.getText().length();
					return;
				}
				if (e.keyCode == SWT.ARROW_LEFT || e.keyCode == SWT.ARROW_RIGHT){
					return;
				}
				if (e.keyCode == SWT.SHIFT || e.keyCode == SWT.HOME || e.keyCode == SWT.END){
					return;
				}
				String text = targetText.getText();
				if (text != null){
					String temp = text;
					if (POLICY_MODEL_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z]","");//only number & chars
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.upperFirst(temp);							
						}
					}
					else if (POLICY_FOLDER_NAME.equals(policy)){
						String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
						temp = replace(text,regEx,"");//special char
						if (temp.length() > 0){
							temp = temp.trim();
						}
					}
					else if (POLICY_OPERATION_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.lowerFirst(temp);							
						}
					}
					else if (POLICY_FREE_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
					}					
					targetText.setText(temp);
					int selectionIndex = targetText.getSelectionCount();
					if (selectionIndex == 0){
						if (currentCursorPostion != -1){
							if (currentTextLength == temp.length()){
								if (currentCursorPostion == 0){
									selectionIndex = currentTextLength;
								}else{
									selectionIndex = currentCursorPostion;									
								}
							}else{
								if (e.keyCode ==  8){
									selectionIndex =currentCursorPostion - 1;
								}else{
									selectionIndex =currentCursorPostion + 1;									
								}
							}
						}else{
							selectionIndex = temp.length();							
						}
					}
		        	targetText.setSelection(selectionIndex);
				}
			}
		});
		
		targetText.addMouseListener(new MouseAdapter() {
			int caretPosition = 0;
			@Override
			public void mouseUp(MouseEvent e) {
				String text = targetText.getText();
				String selectedText = targetText.getSelectionText();
				if (selectedText != null && selectedText.length() > 0){
					return;
				}
				if (text != null){
					String temp = text;
					if (POLICY_MODEL_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z]","");//only number & chars
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.upperFirst(temp);						
						}
					}
					else if (POLICY_FOLDER_NAME.equals(policy)){
						String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
						temp = replace(text,regEx,"");//special char
						if (temp.length() > 0){
							temp = temp.trim();
						}
					}
					else if (POLICY_OPERATION_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars & _
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.lowerFirst(temp);						
						}
					}
					else if (POLICY_FREE_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars & _
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
					}					
					targetText.setText(temp);	
					targetText.setSelection(caretPosition,caretPosition);
					
//					int selectionIndex = targetText.getSelectionCount();
//					if (selectionIndex == 0){
//						selectionIndex = temp.length();							
//					}
//		        	targetText.setSelection(selectionIndex);
				}
			}
			
			public void mouseDown(MouseEvent e) {
				this.caretPosition = targetText.getCaretPosition();
				targetText.setSelection(caretPosition,caretPosition);
			}
		});
		
		
		
		targetText.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				String text = targetText.getText();
				String selectedText = targetText.getSelectionText();
				if (selectedText != null && selectedText.length() > 0){
					return;
				}
				if (text != null){
					String temp = text;
					if (POLICY_MODEL_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z]","");//only number & chars
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.upperFirst(temp);						
						}
					}
					else if (POLICY_FOLDER_NAME.equals(policy)){
						String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
						temp = replace(text,regEx,"");//special char
						if (temp.length() > 0){
							temp = temp.trim();
						}
					}
					else if (POLICY_OPERATION_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars & _
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
						if (temp.length() > 0){
							temp = StringUtil.lowerFirst(temp);						
						}
					}
					else if (POLICY_FREE_NAME.equals(policy)){
						temp = replace(text,"[^\\dA-Za-z_]","");//only number & chars & _
						temp = loopReplaceFirstNumber(temp,"^[^a-zA-Z]"); //remove first number
					}					
					targetText.setText(temp);	
					
//					int selectionIndex = targetText.getSelectionCount();
//					if (selectionIndex == 0){
//						selectionIndex = temp.length();							
//					}
//		        	targetText.setSelection(selectionIndex);
				}
			}
		});
	}
	public static String replace(String src, String regEx, String rep) {
		String result = src;
		Pattern pat = Pattern.compile(regEx);
		Matcher matcher = pat.matcher(src);
		if (matcher.find()) {
			result= matcher.replaceAll(rep);
		} 
		return result;
	}
	public static String loopReplaceFirstNumber(String value,String reg){
		String temp  = replace(value,reg,"");
		if (temp.equals(value)){
			return temp;
		}else{
			return loopReplaceFirstNumber(temp,reg);
		}
	}
}
